package com.gs.m_register

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.gs.common.BaseStateCallback
import com.gs.common.constant.StateCode

class RegisterPersistent(context: Context) {

    private val registerModel by lazy { RegisterModel.getInstance(context) }
    private val handler = Handler(Looper.getMainLooper())

    fun register(phoneNum: String, username: String, password: String, callback: OnDoRegisterStateCallback){
        Thread{
            registerModel.register(phoneNum, username, password) {
                when (it) {
                    StateCode.STATE_LOADING -> {
                        handler.post {
                            callback.onRegisterLoading()
                        }
                    }
                    StateCode.STATE_SUCCESS -> {
                        handler.post {
                            callback.onRegisterSuccess()
                        }
                    }
                    StateCode.STATE_FAILED -> {
                        handler.post {
                            callback.onRegisterFailed()
                        }
                    }
                    StateCode.NETWORK_ERROR -> {
                        handler.post {
                            callback.onNetworkError()
                        }
                    }
                    StateCode.SERVER_ERROR -> {
                        handler.post {
                            callback.onServerError()
                        }
                    }
                    StateCode.UNKNOWN_ERROR -> {
                        handler.post {
                            callback.onUnknownError()
                        }
                    }
                }
            }
        }.start()
    }

    interface OnDoRegisterStateCallback: BaseStateCallback{
        fun onRegisterLoading(){}
        fun onRegisterSuccess()
        fun onRegisterFailed()
    }

    companion object{
        private var instance: RegisterPersistent? = null

        fun getInstance(context: Context): RegisterPersistent {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = RegisterPersistent(context)
                    }
                }
            }
            return instance!!
        }
    }

}